import threading
from concurrent.futures import ThreadPoolExecutor
from requ.conn import *
from other.num_name import bb_name_ming, num_data, fb_name_ming, od, bti_name
from sql.sql_conn import Mysql_data
from sql.sql_state import insert_data, select_gun, insert_data_1
import faulthandler

faulthandler.enable()

data_1 = {
    "command": "request_session",
    "params": {
        "language": "zhh",
        "site_id": "510",
        "release_date": "10/07/2024-11:30"
    },
    "rid": int(time.time() * 10000)
}


# {
#     "command": "request_session",
#     "params": {
#         "language": "zhh",
#         "site_id": "510",
#         "release_date": "10/07/2024-11:30"
#     },
#     "rid": int(time.time() * 10000)
# }


class Conn(Mysql_data):

    def bb_conn_1(self):
        mm = 0
        while True:
            try:
                BB_HEADERS = {
                    'Accept-Encoding': 'gzip, deflate, br',
                    'Accept-Language': 'zh,zh-CN;q=0.9',
                    'Cache-Control': 'no-cache',
                    'Connection': 'Upgrade',
                    'Host': 'ws.quickintegrationbest.net',
                    # 'Origin': 'https://web.quickintegrationbest.net',
                    'Pragma': 'no-cache',
                    'Sec-Websocket-Extensions': 'permessage-deflate; client_max_window_bits',
                    # 'Sec-Websocket-Key': 'LGbJdZVHqZScFMFG/YDVIw==',
                    # 'Sec-Websocket-Version': '13',
                    'Upgrade': 'websocket',
                    # 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36',
                    "User-Agent": random.choice(USER_AGENT_LIST),
                }
                #     {
                #     'Host': 'socks.cdncnregions.com',
                #     'Connection': 'Upgrade',
                #     'Pragma': 'no-cache',
                #     'Cache-Control': 'no-cache',
                #     'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0',
                #     'Upgrade': 'websocket',
                #     'Origin': 'https://web.fastcnregions.com',
                #     'Sec-WebSocket-Version': '13',
                #     'Accept-Encoding': 'gzip, deflate, br, zstd',
                #     'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6',
                #     'Sec-WebSocket-Key': 'B/jR4+qjU9/VZwjkZzucfg==',
                #     'Sec-WebSocket-Extensions': 'permessage-deflate; client_max_window_bits',
                # }

                BBURL = 'wss://ws.quickintegrationbest.net'  #'wss://ws.cdnintegrations.com/'# "wss://socks.cdncnregions.com/"
                # wss://socks.cdncnregions.com/

                # PROXIES = {'http': random.choice(IP_LIST)} #
                ws = create_connection(url=BBURL, timeout=5, headers=BB_HEADERS,
                                       sslopt={'cert_reqs': ssl.CERT_NONE})
                # ,http_proxy_host="113.228.89.67", http_proxy_port="4231", proxy_type="http")
                ws.send(json.dumps(data_1))
                ws.recv()
                # print(a)
                return ws

            except Exception as e:
                mm += 1
                print('BB连接异常：', e)
                print("BB正在重新连接...")
                if mm == 2:
                    print("退出重新连接")
                    return None
                continue

    def bb_handle(self, game_id, ws, t1, t2, name_t='bb'):  # ):,ret, region_id, competition_id
        data_2 = {
            "command": "get",
            "params": {
                "source": "betting",
                "what": {
                    "competition": ["name"],
                    "game": ["info", "team1_name", "team2_name", "is_blocked",'stats'],
                    "market": ["name"],
                    "event": ["type_1", "name", "price", "base"]},
                "where": {"game": {"id": game_id[0]}, "competition": {"id": game_id[2]},
                          "region": {"id": game_id[1]}, "sport": {"id": 1}},
                "subscribe": "true"},
            "rid": int(round(time.time(), 5) * 100000)

        }
        data_3 = {
            "command": "unsubscribe",
            "params": {
                "subid": "-2374533034402152619"
            },
            "rid": int(round(time.time(), 5) * 100000)
        }
        # ws.send(json.dumps(data_3))
        ws.send(json.dumps(data_2))
        ret = ws.recv()
        res_data = json.loads(ret.encode().decode("utf8"))  # 'unicode-escape'
        # print(res_data)
        try:
            competition = res_data["data"]["data"]["competition"]
        except Exception as e:
            print("bb_handle:bb_data", e)
            return None

        data_list_quan_daxiao = []
        data_list_ban_daxiao = []
        data_list_quan_ran = []
        data_list_ban_ran = []
        # print("BB已连接")
        for competition_key in competition:
            league_name = competition[competition_key]["name"]  # 联赛名称
            game = competition[competition_key]["game"]

            for game_key in game:
                game_data = game[game_key]
                is_blocked = game_data["is_blocked"]
                if is_blocked == 0:
                    # print(is_blocked)
                    team1_name = game_data["team1_name"]  # 队伍名称
                    team2_name = game_data["team2_name"]  # 队伍名称
                    info_score = game_data["info"]["score1"] + ":" + game_data["info"]["score2"]  # 得分
                    score = float(game_data["info"]["score1"]) - float(game_data["info"]["score2"])
                    try:
                        corner = str(game_data['stats']['corner']['team1_value'])+":"+str(game_data['stats']['corner']['team2_value']) # 角球
                        stats = float(game_data['stats']['corner']['team1_value']) - float(game_data['stats']['corner']['team2_value'])
                    except:
                        corner = -1
                        stats = 0
                    try:
                        current_game_time = game_data["info"]["current_game_time"]  # 比赛进行时间
                    except:
                        current_game_time = 0
                    market = game_data["market"]
                    if market == {}:
                        return None
                    for market_key in market:
                        market_name = bb_name_ming(market[market_key]["name"])  # 类别    全场大小'全场让分
                        market_name_1 = market[market_key]["name"]

                        event = market[market_key]["event"]
                        event_list = []

                        if (
                                "犯规" not in market_name_1 and "边线球" "外球" not in market_name_1 and "边线球" not in market_name_1 and
                                "越位" not in market_name_1 and "球员" not in market_name_1 and "方式" not in market_name_1 and
                                "首个" not in market_name_1 and "点球" not in market_name_1 and "剩余" not in market_name_1 and
                                "晋级" not in market_name_1 and "透过" not in market_name_1 and "分钟" not in market_name_1 and
                                "单" not in market_name_1 and "退款" not in market_name_1 and "进" not in market_name_1 and
                                "最高" not in market_name_1 and "/" not in market_name_1 and "个" not in market_name_1 and
                                "三" not in market_name_1 and "项" not in market_name_1 and "胜" not in market_name_1 and
                                "胆" not in market_name_1 and "区间" not in market_name_1 and "精确值" not in market_name_1 and
                                "或" not in market_name_1 and "球门" not in market_name_1 and "哪一队" not in market_name_1):
                            # print(market_name,"-------------",market_name_1,"++++++++++++")
                            for event_key in event:
                                event_price = round(float(event[event_key]["price"]), 2)  # 倍率 类别名称得分
                                event_name = event[event_key]['name'].strip()  # 类别名称 大  小
                                if market_name != None and (
                                        "大" in market_name or "让" in market_name or "总得分" in market_name):
                                    try:
                                        event_base = event[event_key]["base"]  # 类别名称得分前面那个数据  1.5/2   2.25
                                    except:
                                        event_base = None


                                    if event[event_key]['type_1'] == "Away":
                                        if "角让" in market_name:
                                            event_base -= stats
                                        else:
                                            event_base -= score
                                    if event[event_key]['type_1'] == "Home":
                                        if "角让" in market_name:
                                            event_base += stats
                                        else:
                                            event_base += score

                                    if ".25" in str(event_base) or ".75" in str(event_base):
                                        event_base = num_data(event_base)
                                    if '让' in market_name and event_base != 0 and "-" not in str(event_base):
                                        event_base = "+" + str(event_base)
                                    event_list.append((event_name, event_base, round(event_price - 1, 2)))
                                elif market_name != None and "独赢" in market_name:
                                    event_list.append([event_name, event_price])
                                else:
                                    event_list.append([event_name, round(event_price - 1, 2)])
                            try:
                                if len(event_list[0]) > 2:
                                    data_all = t1, league_name, current_game_time, info_score, team1_name, team2_name, market_name, \
                                        event_list[0][0], event_list[0][1], event_list[0][2], event_list[1][0], \
                                        event_list[1][1], event_list[1][2], t2, game_key, corner
                                    # print(data_all)

                                    if "全" in market_name:
                                        if "让" in market_name:
                                            data_list_quan_ran.append(data_all)
                                        else:
                                            data_list_quan_daxiao.append(data_all)
                                            # if ("小" in data_all[7] and float(data_all[9]) >= 0.3 and int
                                            #     (data_all[2]) >= 89) or \
                                            #         ("小" in data_all[10] and float(data_all[12]) >= 0.3 and int(
                                            #             data_all[2]) >= 89):
                                            #     pass


                                    else:
                                        if "让" in market_name:
                                            data_list_ban_ran.append(data_all)
                                        else:
                                            data_list_ban_daxiao.append(data_all)

                            except Exception as e:
                                print("bb_handle_game: ", e)
                                pass

        quan = name_t
        ban = '{}_ban'.format(name_t)
        ran = '{}_ran'.format(name_t)
        b_ran = '{}_ban_ran'.format(name_t)
        # print(quan,ban,ran,b_ran)
        if len(data_list_quan_daxiao) != 0:
            idd = insert_data_1(quan)
            self.run_sql(idd, data_list_quan_daxiao)

        if data_list_ban_daxiao != []:
            idd2 = insert_data_1(ban)
            self.run_sql(idd2, data_list_ban_daxiao)
            # print(idd2)
        if len(data_list_quan_ran) != 0:
            idf3 = insert_data_1(ran)
            self.run_sql(idf3, data_list_quan_ran)
            # print(idf3)
        if data_list_ban_ran != []:
            idd4 = insert_data_1(b_ran)
            self.run_sql(idd4, data_list_ban_ran)

    def fb_handle(self, game_id, t1, t2):
        global na, fb_data
        json_data = {
            "languageType": "CMN",
            "matchId": game_id
        }
        ss = requests.Session()
        url = random.choice(FB_URL_L)
        fb_conn = fb_connect(FB_URL, json_data, ss)
        # print(url)
        # ss.trust_env = False
        try:
            i = fb_conn["data"]
        except:
            print(fb_conn)
            return
        data_quan_da = []
        data_ban_da = []
        data_quan_ran = []
        data_ban_ran = []
        lianshan_name = i["lg"]["na"]  # 联赛名称
        # print(lianshan_name)
        fb_id = i["id"]
        bisai_duiwu_name1 = i["ts"][0]["na"]  # 队伍名称
        bisai_duiwu_name2 = i["ts"][1]["na"]  # 队伍名称
        try:
            nsg = str(i["nsg"][0]["sc"][0]) + ":" + str(i["nsg"][0]["sc"][1])  # 得分
        except:
            nsg = -1
        # try:
        #     nsg_jiao = str(i["nsg"][3]["sc"][0]) + ":" + str(i["nsg"][3]["sc"][1])  # 角
        # except:
        #     nsg_jiao = -1
        try:
            mc_s = i["mc"]["s"] // 60  # 比赛进行时间
        except:
            mc_s = -1
        mg = i["mg"]
        for j in mg:
            nm = fb_name_ming(j["nm"], bisai_duiwu_name1, bisai_duiwu_name2)  # 类别 让球
            for k in j["mks"]:
                ss = k["ss"]
                if ss != 0:
                    # print(ss)
                    na_li_od = []
                    for l in k["op"]:
                        try:
                            na = l["na"]  # 类别名字  "大",
                        except:
                            pass

                        try:
                            li = l["li"]  # "3/3.5"
                        except:
                            li = l["nm"]
                        try:
                            od = round(float(l["od"]) - 1, 2)  # 倍率
                        except:
                            od = -1
                        na_li_od.append((na, li, od))

                    excluded_keywords = [
                        '点球', '方式', '首个', '最多', '总', '粒',
                        '半场/全场', '净胜', '机会', '双', '胜平',
                        '零失', '独赢', '波胆', '剩余', '退款',
                        '精确', '获胜', '任意', '射正', '正确比分',
                        '进球', '分钟', '获得', '范围', '第'
                    ]

                    if all(keyword not in j["nm"] for keyword in excluded_keywords):
                        # print(j["nm"], "++++++++++++++++++",nm )
                        try:
                            fb_data = t1, lianshan_name, mc_s, nsg, bisai_duiwu_name1, bisai_duiwu_name2, nm, \
                                na_li_od[0][0], na_li_od[0][1], na_li_od[0][2], na_li_od[1][0], na_li_od[1][1], \
                                na_li_od[1][2], t2, fb_id
                            # print(fb_data)
                        except:
                            # print(nm, na_li_od)
                            pass
                        if nm != None:
                            # print(j["nm"],"------------------",nm)
                            if "全" in nm:
                                if "让" in nm:
                                    data_quan_ran.append(fb_data)
                                else:
                                    data_quan_da.append(fb_data)
                                    if ("小" in fb_data[7] and float(fb_data[9]) >= 0.6 and int(
                                            fb_data[2]) >= 85) or (
                                            "小" in fb_data[10] and float(fb_data[12]) >= 0.6 and int(
                                        fb_data[2]) >= 85):
                                        pass
                            else:
                                if "让" in nm:
                                    data_ban_ran.append(fb_data)
                                else:
                                    data_ban_da.append(fb_data)

        if len(data_quan_da) != 0:
            ll = insert_data("fb")
            self.run_sql(ll, data_quan_da)
        if data_ban_da != []:
            ll1 = insert_data("fb_ban")
            self.run_sql(ll1, data_ban_da)
        if len(data_quan_ran) != 0:
            ll2 = insert_data("fb_ran")
            self.run_sql(ll2, data_quan_ran)
        if data_ban_ran != []:
            ll3 = insert_data("fb_ban_ran")
            self.run_sql(ll3, data_ban_ran)
        # mysqkk.loop_colos()

        # return data_quan_da, data_ban_da, data_quan_ran, data_ban_ran

    def ss_handle(self, t1, t2):
        data = ss_comm()
        events = data['events']
        data_list_quan_daxiao = []
        data_list_ban_daxiao = []
        data_list_quan_ran = []
        data_list_ban_ran = []
        for eve in events:
            for eve_data in eve:
                eveid = eve_data['eveid']  # 比赛ID

                # dt = eve_data['dt']  # 开赛时间
                lgecapt = eve_data['lgecapt']  # 联赛名称
                tacapt = eve_data['tacapt']  # 主队
                tbcapt = eve_data['tbcapt']  # 客队
                evetm = eve_data["rbinfo"]["evetm"]  # 时间
                rbinfo_scoa_scob = str(eve_data["rbinfo"]["scoa"]) + ":" + str(eve_data["rbinfo"]["scob"])  # 得分

                mm = 0
                if "角球" in tbcapt:
                    '科隆'
                    lgecapt = lgecapt[:-7]
                    tacapt = tacapt[:-4]
                    tbcapt = tbcapt[:-4]
                    mm = 2

                if eve_data['od'] != []:
                    od_1 = eve_data['od']['1']

                    od_data = od(od_1, tacapt, tbcapt, mm)
                    if od_data != []:
                        for i in od_data:
                            data_all = t1, lgecapt, evetm, rbinfo_scoa_scob, tacapt, tbcapt, i[0], i[1], i[2], i[3], i[
                                4], i[5], i[6], t2, eveid
                            # print(data_all)
                            if '让' in i[0]:
                                data_list_quan_ran.append(data_all)
                            else:
                                data_list_quan_daxiao.append(data_all)

                    try:
                        od_2 = eve_data['od']['2']
                        mm = mm + 1
                        od_data_ban = od(od_2, tacapt, tbcapt, mm)
                        if od_data_ban != []:
                            for i in od_data_ban:
                                data_all = t1, lgecapt, evetm, rbinfo_scoa_scob, tacapt, tbcapt, i[0], i[1], i[2], i[3], \
                                    i[4], \
                                    i[5], i[6], t2, eveid
                                # print(data_all)
                                if '让' in i[0]:
                                    data_list_ban_ran.append(data_all)
                                else:
                                    data_list_ban_daxiao.append(data_all)

                    except Exception as e:
                        # print("od_2 = eve_data['od']['2']", e)
                        pass
        # t5 = time.time()
        if len(data_list_quan_daxiao) != 0:
            idd = insert_data("ss")
            self.run_sql(idd, data_list_quan_daxiao)
            # print(idd)
        if data_list_ban_daxiao != []:
            idd2 = insert_data("ss_ban")
            self.run_sql(idd2, data_list_ban_daxiao)
            # print(idd2)
        if len(data_list_quan_ran) != 0:
            idf3 = insert_data("ss_ran")
            self.run_sql(idf3, data_list_quan_ran)
            # print(idf3)
        if data_list_ban_ran != []:
            idd4 = insert_data("ss_ban_ran")
            self.run_sql(idd4, data_list_ban_ran)
            # print(idd4)
        # print("***",time.time()-t5)

    def bti_handle(self, req_data):
        data = req_data[0]
        liansai_name = data[22]  # 联赛名称
        bisai_name = data[8]
        duiwu_name = {}  # 队伍名称 # Home  Away
        for name in bisai_name:
            bisai_name = name[1]
            bisai_name_leibie = name[2]  # Home  Away
            duiwu_name[bisai_name_leibie] = bisai_name
        score = data[12][0] + ":" + data[12][1]  # 比分
        game_all = data[20]
        game_list = []
        game_list_ban = []
        game_list_ran = []
        game_list_ran_ban = []

        for game in game_all:
            leibie = game[1]  # 全场 角球 大小盘
            if ("进球数" in leibie and "大小" in leibie) or (
                    "进球数" not in leibie and "三项" not in leibie and "净胜比分" not in leibie
                    and "失球" not in leibie and "正确比分" not in leibie and "附加" not in leibie
                    and "附加" not in leibie and "进球最多" and "两队" not in leibie and "半场/全场" not in leibie
                    and "第" not in leibie and "单" not in leibie and "剩余" not in leibie and ":" not in leibie
                    and "平局" not in leibie and "分钟" not in leibie and "1X2" not in leibie and "机会" not in leibie
                    and "首先" not in leibie):
                leibie = bti_name(leibie, duiwu_name)

                beilu = game[13]
                beilu_list = []
                n = 0
                for i in beilu:
                    beilu_num = i[6]  # 0.83
                    if beilu_num != 0:
                        type_name = i[11]["ZH"]  # 大于  Home Away
                        if "大" in type_name or "小" in type_name:
                            type_name = type_name[0]
                        else:
                            type_name = duiwu_name[type_name]

                        qiushu = i[16]  # 0.5   1   1.25
                        if "25" in str(qiushu) or "75" in str(qiushu):
                            qiushu = num_data(qiushu)
                        data_num = type_name, qiushu, round(beilu_num - 1, 2)
                        n += 1
                        beilu_list.append(data_num)
                        if n == 2:
                            n = 0
                            data_all = self.t1, liansai_name, score, duiwu_name["Home"], duiwu_name["Away"], leibie, \
                                beilu_list[0][0], beilu_list[0][1], beilu_list[0][2], beilu_list[1][0], \
                                beilu_list[1][1], beilu_list[1][2], self.t2
                            if "全" in leibie:
                                if "让" in leibie:
                                    if data_all not in game_list_ran:
                                        game_list_ran.append(data_all)
                                else:
                                    if data_all not in game_list:
                                        game_list.append(data_all)
                            else:
                                if "让" in leibie:
                                    if data_all not in game_list_ran_ban:
                                        game_list_ran_ban.append(data_all)
                                else:
                                    if data_all not in game_list_ban:
                                        game_list_ban.append(data_all)
            # else:
            #     print(leibie)

        # mysqkk = MysqlBb()
        # if len(game_list) != 0:
        # mysqkk.run("bti", game_list)
        # if game_list_ban != []:
        #     mysqkk.run("bti_ban", game_list_ban)
        # if len(game_list_ran) != 0:
        #     mysqkk.run("bti_ran", game_list_ran)
        # if game_list_ran_ban != []:
        #     mysqkk.run("bti_ban_ran", game_list_ran_ban)

    def db_handle(self, data, game_id):

        data_all = json.loads(data)['data']
        quan = '全场大小'
        ban = '上半场大小'
        ran = '全场让'
        bran = '上半场让'
        quan_jiao = '全场角球大小'
        ban_jiao = '上半角球大小'
        ran_jiao = '全场角让'
        bran_jiao = '上半场角让'
        da = []
        bda = []
        rang = []
        brang = []

        for data_a in data_all:
            tn = data_a['tn']  # 联赛名
            if 'VS' in tn:
                break
            self.mid = int(data_a['mid'])
            if self.mid not in game_id:
                continue
            mhn = data_a['mhn']  # 主队
            man = data_a['man']  # 客队
            try:
                msc = data_a['msc'][0][3:]  # S1 比分？？？？？
                # S12 黄      S5 角球
            except:
                # print(data_a['msc'])
                msc = -1
                # self.msc1 = data_a['msc'][16]  # 时间？？？？？


            hpsData = data_a['hpsData'][0]
            hps = hpsData['hps']
            hl_quan_rang = hps[1]['hl']
            ol_quan_rang = self.db_ran(hl_quan_rang, mhn, man)
            hl_ban_rang = hps[4]['hl']
            ol_ban_rang = self.db_ran(hl_ban_rang, mhn, man)
            hl_quan_da = hps[2]['hl']
            ol_quan_da = self.db_da(hl_quan_da)
            hl_ban_da = hps[5]['hl']
            ol_ban_da = self.db_da(hl_ban_da)
            da.append(self.db_print_details(tn, msc, mhn, man, quan, ol_quan_da))
            bda.append(self.db_print_details(tn, msc, mhn, man, ban, ol_ban_da))
            rang.append(self.db_print_details(tn, msc, mhn, man, ran, ol_quan_rang))
            brang.append(self.db_print_details(tn, msc, mhn, man, bran, ol_ban_rang))

            hpsAdd = hpsData['hpsAdd']
            hl_add_quan_rang = hpsAdd[1]['hl']
            for hp in hl_add_quan_rang:
                ol_add_quan_rang = self.db_ran(hp, mhn, man)
                rang.append(self.db_print_details(tn, msc, mhn, man, ran, ol_add_quan_rang))
            hl_add_ban_rang = hpsAdd[4]['hl']
            for hp in hl_add_ban_rang:
                ol_add_ban_rang = self.db_ran(hp, mhn, man)
                brang.append(self.db_print_details(tn, msc, mhn, man, bran, ol_add_ban_rang))
            hl_add_quan_da = hpsAdd[2]['hl']
            for hp in hl_add_quan_da:
                ol_add_quan_da = self.db_da(hp)
                da.append(self.db_print_details(tn, msc, mhn, man, quan, ol_add_quan_da))
            hl_add_ban_da = hpsAdd[5]['hl']
            for hp in hl_add_ban_da:
                ol_add_ban_da = self.db_da(hp)
                bda.append(self.db_print_details(tn, msc, mhn, man, ban, ol_add_ban_da))
            # return
            hpsCorner = data_a['hpsCorner']  # 角球
            if hpsCorner:
                hl_quan_rang_jiao = hpsCorner[1]['hl']
                ol_quan_rang_jiao = self.db_ran(hl_quan_rang_jiao, mhn, man)
                hl_ban_rang_jiao = hpsCorner[4]['hl']
                ol_ban_rang_jiao = self.db_ran(hl_ban_rang_jiao, mhn, man)
                hl_quan_da_jiao = hpsCorner[2]['hl']
                ol_quan_da_jiao = self.db_da(hl_quan_da_jiao)
                hl_ban_da_jiao = hpsCorner[5]['hl']
                ol_ban_da_jiao = self.db_da(hl_ban_da_jiao)
                da.append(self.db_print_details(tn, msc, mhn, man, quan_jiao, ol_quan_da_jiao))
                bda.append(self.db_print_details(tn, msc, mhn, man, ban_jiao, ol_ban_da_jiao))
                rang.append(self.db_print_details(tn, msc, mhn, man, ran_jiao, ol_quan_rang_jiao))
                brang.append(self.db_print_details(tn, msc, mhn, man, bran_jiao, ol_ban_rang_jiao))

        da_list = [item for item in da if item is not None]
        rang_list = [item for item in rang if item is not None]
        brang_list = [item for item in brang if item is not None]
        bda_list = [item for item in bda if item is not None]
        if da_list:
            ll3 = insert_data("od")
            self.run_sql(ll3, da_list)
            # print(da_list)
        if rang_list:
            ll3 = insert_data("od_ran")
            self.run_sql(ll3, rang_list)
            # print(rang_list)
        if brang_list:
            ll3 = insert_data("od_ban_ran")
            self.run_sql(ll3, brang_list)
            # print(brang_list)
        if bda_list:
            ll3 = insert_data("od_ban")
            self.run_sql(ll3, bda_list)
            # print(bda_list)

            # return

    def db_print_details(self, tn, msc, mhn, man, value, flag):
        if flag:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            # print(t1, tn, msc, mhn, man, value, flag, t2, self.mid)
            try:
                data_a = t1, tn, -1, msc, mhn, man, value, flag[0][0], flag[0][1], flag[0][2], flag[1][0], flag[1][1], \
                flag[1][2], t2, self.mid
            except Exception as e:
                print(tn, -1, msc, mhn, man, value, flag)
                print(e)
                return
            return data_a
        else:
            return

    def db_ran(self, hl_rang, mhn, man):
        ol_list = []
        if hl_rang == {}:
            return ol_list
        ol = hl_rang['ol']
        for o_l in ol:
            n = 1
            onb = o_l['onb']  # "+0/0.5"
            try:
                ov2 = o_l['ov2']  # "0.81",.
                if float(ov2) < 0.0:
                    ov2 = db_pl[ov2]

                else:
                    ov2 = round(float(ov2) + 0.02, 2)
            except:
                # ov2 = '-1'
                return ol_list
            if n == 1:
                ol_list.append((mhn, onb, ov2))
                n += 1
            else:
                ol_list.append((man, onb, ov2))
        return ol_list

    def db_da(self, hl_rang):
        ol_list = []
        if hl_rang == {}:
            return ol_list
        ol = hl_rang['ol']
        for o_l in ol:
            onb = o_l['onb']  # "2.5/3"
            try:
                ov2 = o_l['ov2']  # "0.81",
                if float(ov2) < 0.0:
                    ov2 = db_pl[ov2]
                else:
                    ov2 = round(float(ov2) + 0.02, 2)
            except:
                # ov2 = '-1'
                return ol_list
            onbl = o_l['onbl'][0]  # "小 "
            ol_list.append((onbl, onb, ov2))

        return ol_list

    def run_fb(self, game_id, t1, t2):
        # ss = requests.Session()
        # ss.trust_env = False
        nn = 0
        # ss = requests.Session()
        with ThreadPoolExecutor(5) as t:
            for i in game_id:
                t.submit(self.fb_handle, i, t1, t2)
                # t.submit(asyncio.run(self.main(i)))
                nn += 1
        # ss.trust_env = False
        # ss.close()
        # asyncio.run(self.main(game_id))
        print(nn, "FB OK")

        # g_lista = []
        # # start_time = time.time()
        # for i in game_id:
        #     g = gevent.spawn(self.fb_handle, i, t1, t2)
        #     g_lista.append(g)
        #
        # [a.join() for a in g_lista]
        # print(len(g_lista), 'FB OK')

    def run_bb(self, get_id, t1, t2):
        nn = 0
        try:
            ws = self.bb_conn_1()
            # with ThreadPoolExecutor(2) as t:
            #     for i_d in get_id:
            #         t.submit(self.bb_handle, i_d, ws, t1, t2)
            #         nn += 1
            for i_d in get_id:
                # time.sleep(0.2)
                self.bb_handle(i_d, ws, t1, t2)
                nn += 1
            ws.close()
        except Exception as e:
            print("ws", e)
        print(nn, "BB OK")

    def run_bb_2(self, get_id, t1, t2):
        nn = 0
        try:
            ws = self.bb_conn_1()
            with ThreadPoolExecutor(4) as t:
                for i_d in get_id:
                    time.sleep(0.1)
                    t.submit(self.bb_handle, i_d, ws, t1, t2)
                    nn += 1
        except Exception as e:
            print("ws", e)
        print(nn, "BB OK")

    def run_ss(self, t1, t2):
        # t1 = time.strftime("%Y-%m-%d %X", time.localtime())
        # t2 = time.time()
        try:
            self.ss_handle(t1, t2)
            print('SS OK', time.time() - t2)
            time.sleep(1)
        except Exception as e:
            print("SS", e)

    def run_lu(self, get_id, t1, t2):
        nn = 0
        try:
            ws = lu_conn()
            with ThreadPoolExecutor(1) as t:
                for i_d in get_id:
                    t.submit(self.bb_handle, i_d, ws, t1, t2, 'xy')
                    nn += 1
            ws.close()
        except Exception as e:
            print("ws", e)
        print(nn, "LU OK")


class Run(Conn):
    # def __init__(self):
    #     super().__init__()
    #     # self.bb_fb()
    #     # self.bb_ss()
    #     self.bb_fb_1()

    def bb_fb(self, n1, n2):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                fb_bb_id = select_gun("FB_game_id,BB_game_id,BB_region_id,BB_competition_id", 'bisai_fb_bb_duiwu')
                id_all = self.run_sql(fb_bb_id)
                if len(id_all) != 0:
                    fb_id = [i[0] for i in id_all][::-1][n1:n2]  #
                    bb_id = [(i[1], i[2], i[3]) for i in id_all][::-1][n1:n2]  # []
                    th_bb = threading.Thread(target=self.run_bb, args=(bb_id, t1, t2))
                    # th_fb = threading.Thread(target=self.run_fb, args=([fb_id], t1, t2))

                    aa = []
                    aa.append(th_bb)
                    id_nun = len(fb_id) // 20
                    num = len(fb_id) % 20
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    for i in range(pego):
                        th_1 = threading.Thread(target=self.run_fb, args=(fb_id[i * 20:(i + 1) * 20], t1, t2))
                        th_1.start()
                        aa.append(th_1)
                    th_bb.start()
                    for i in aa:
                        i.join()
                    # fb_th.join()
                    # th_bb.join()
                    print(time.time() - t2)
                    # if len(get_id) <= 25:
                    time.sleep(1.5)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def bb_fb_1(self, n1, n2):
        bisai_num = n1

        fb_bb_id = select_gun("FB_game_id,BB_game_id,BB_region_id,BB_competition_id", 'bisai_fb_bb_duiwu')
        id_all = self.run_sql_1(fb_bb_id)
        fb_id = [i[0] for i in id_all][::-1][bisai_num:n2]  # [:30]
        bb_id = [(i[1], i[2], i[3]) for i in id_all][::-1][bisai_num:n2]  # []
        print("***")
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                if int(time.time()) % 120 < 10:
                    fb_bb_id = select_gun("FB_game_id,BB_game_id,BB_region_id,BB_competition_id", 'bisai_fb_bb_duiwu')
                    id_all = self.run_sql_1(fb_bb_id)
                    fb_id = [i[0] for i in id_all][::-1][bisai_num:]  # [:30]
                    bb_id = [(i[1], i[2], i[3]) for i in id_all][::-1][bisai_num:]
                    print("***")
                print('--------------', len(id_all))
                if len(id_all) > bisai_num:

                    th_bb = threading.Thread(target=self.run_bb, args=(bb_id, t1, t2))
                    # th_fb = threading.Thread(target=self.run_fb, args=([fb_id], t1, t2))

                    aa = []

                    id_nun = len(fb_id) // 20
                    num = len(fb_id) % 20
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    th_bb.start()
                    # for i in range(pego):[i * 20:(i + 1) * 20]
                    th_1 = threading.Thread(target=self.run_fb, args=(fb_id, t1, t2))
                    th_1.start()
                    aa.append(th_1)
                    aa.append(th_bb)
                    for i in aa:
                        i.join()
                    # fb_th.join()
                    # th_bb.join()
                    print(time.time() - t2)
                    # if len(get_id) <= 25:
                    time.sleep(0.5)
                else:
                    print("等等")
                    time.sleep(90)
            except Exception as e:
                print(e)
                time.sleep(20)

    def ss_fb(self):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            fb_bb_id = select_gun("FB_game_id", 'bisai_fb_ss_duiwu')
            id_all = self.run_sql(fb_bb_id)
            if len(id_all) != 0:
                fb_id = [i[0] for i in id_all]  # [:30]
                aa = []
                id_nun = len(fb_id) // 5
                num = len(fb_id) % 5
                if num == 0:
                    pego = id_nun
                else:
                    pego = id_nun + 1
                for i in range(pego):
                    th_1 = threading.Thread(target=self.run_fb, args=(fb_id[i * 5:(i + 1) * 5], t1, t2))
                    th_1.start()
                    aa.append(th_1)

                self.run_ss(t1, t2)
                for i in aa:
                    i.join()

            time.sleep(1)

    def bb_ss(self):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                fb_bb_id = select_gun("BB_game_id,BB_region_id,BB_competition_id", 'bisai_fb_bb_duiwu')
                id_all = self.run_sql(fb_bb_id)
                if len(id_all) != 0:

                    bb_id = [(i[0], i[1], i[2]) for i in id_all]  # []
                    th_bb = threading.Thread(target=self.run_bb, args=(bb_id, t1, t2))
                    # th_fb = threading.Thread(target=self.run_fb, args=([fb_id], t1, t2))
                    th_bb.start()

                    self.run_ss(t1, t2)
                    th_bb.join()
                    print(time.time() - t2)

                    time.sleep(1)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def lu_fb(self, n1, n2):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                fb_lu_id = select_gun("FB_game_id,BB_game_id,BB_region_id,BB_competition_id", 'bisai_fb_bb_duiwu')
                id_all = self.run_sql_1(fb_lu_id)
                if len(id_all) != 0:
                    fb_id = [i[0] for i in id_all][::-1][n1:n2]
                    lu_id = [(i[1], i[2], i[3]) for i in id_all][::-1][n1:n2]
                    th_lu = threading.Thread(target=self.run_lu, args=(lu_id, t1, t2))
                    # th_fb = threading.Thread(target=self.run_fb, args=([fb_id], t1, t2))
                    aa = []
                    th_lu.start()
                    aa.append(th_lu)
                    # th_lu.join()
                    id_nun = len(fb_id) // 5
                    num = len(fb_id) % 5
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    for i in range(pego):
                        th_1 = threading.Thread(target=self.run_fb, args=(fb_id[i * 5:(i + 1) * 5], t1, t2))
                        th_1.start()
                        aa.append(th_1)

                    for i in aa:
                        i.join()
                    # fb_th.join()
                    # th_lu.join()
                    print(time.time() - t2)
                    # if len(get_id) <= 25:
                    time.sleep(1.5)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def lu(self, n1, n2):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                fb_bb_id = select_gun("BB_game_id,BB_region_id,BB_competition_id", 'bisai_fb_bb_duiwu')
                id_all = self.run_sql_2(fb_bb_id)
                lu_id = [(i[0], i[1], i[2]) for i in id_all][::-1][n1:n2]  #
                if len(lu_id) != 0:
                    # self.run_lu(lu_id, t1, t2)
                    aa = []
                    id_nun = len(lu_id) // 5
                    num = len(lu_id) % 5
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    for i in range(pego):
                        th_1 = threading.Thread(target=self.run_lu, args=(lu_id[i * 5:(i + 1) * 5], t1, t2))
                        th_1.start()
                        aa.append(th_1)
                    for i in aa:
                        i.join()
                    print(time.time() - t2)
                    # if len(get_id) <= 25:
                    time.sleep(1.5)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def fb(self, n1, n2, bisai_fb_bb_duiwu):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                fb_bb_id = select_gun("FB_game_id", bisai_fb_bb_duiwu)
                id_all = self.run_sql_2(fb_bb_id)
                fb_id = [i[0] for i in id_all][::-1][n1:n2]  #
                if len(fb_id) != 0:
                    aa = []
                    id_nun = len(fb_id) // 10
                    num = len(fb_id) % 10
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    for i in range(pego):
                        th_1 = threading.Thread(target=self.run_fb, args=(fb_id[i * 10:(i + 1) * 10], t1, t2))
                        th_1.start()
                        aa.append(th_1)

                    for i in aa:
                        i.join()
                    print(time.time() - t2)
                    time.sleep(1.5)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def fb2(self, n1, n2):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                fb_bb_id = select_gun("FB_game_id", 'bisai_fb_bb_duiwu')
                id_all = self.run_sql(fb_bb_id)
                fb_id = [i[0] for i in id_all][::-1][n1:n2]  #
                if len(fb_id) != 0:
                    aa = []
                    id_nun = len(fb_id) // 10
                    num = len(fb_id) % 10
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    for i in range(pego):
                        th_1 = threading.Thread(target=self.run_fb, args=(fb_id[i * 10:(i + 1) * 10], t1, t2))
                        th_1.start()
                        aa.append(th_1)

                    for i in aa:
                        i.join()
                    print(time.time() - t2)
                    time.sleep(1.5)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def fb_3(self, n1, n2):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                fb_bb_id = "SELECT game_id FROM bisai_get_fb WHERE is_disabled != 0"
                id_all = self.run_sql_2(fb_bb_id)
                fb_id = [i[0] for i in id_all][::-1][n1:n2]  #
                if len(fb_id) != 0:
                    aa = []
                    id_nun = len(fb_id) // 10
                    num = len(fb_id) % 10
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    for i in range(pego):
                        th_1 = threading.Thread(target=self.run_fb, args=(fb_id[i * 10:(i + 1) * 10], t1, t2))
                        th_1.start()
                        aa.append(th_1)

                    for i in aa:
                        i.join()
                    print(time.time() - t2)
                    time.sleep(1.5)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def bb(self, n1, n2, bisai_fb_bb_duiwu):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                # sql = "SELECT game_id,region_id,competition_id FROM bisai_get_bb WHERE is_disabled != 0"
                # idall = self.run_sql_2(sql)
                fb_bb_id = select_gun("BB_game_id,BB_region_id,BB_competition_id", bisai_fb_bb_duiwu)
                id_all = self.run_sql_2(fb_bb_id)
                bb_id = [(i[0], i[1], i[2]) for i in id_all][::-1][n1:n2]  # []

                if len(bb_id) != 0:
                    # self.run_bb(bb_id, t1, t2)

                    aa = []
                    id_nun = len(bb_id) // 10
                    num = len(bb_id) % 10
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    for i in range(pego):
                        th_1 = threading.Thread(target=self.run_bb, args=(bb_id[i * 10:(i + 1) * 10], t1, t2))
                        th_1.start()
                        aa.append(th_1)

                    for i in aa:
                        i.join()
                    print(time.time() - t2)
                    time.sleep(1)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def bb_2(self, n1, n2, bisai_fb_bb_duiwu):
        ws = self.bb_conn_1()
        mm = 0
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:
                fb_bb_id = select_gun("BB_game_id,BB_region_id,BB_competition_id", bisai_fb_bb_duiwu)
                id_all = self.run_sql(fb_bb_id)
                bb_id = [(i[0], i[1], i[2]) for i in id_all][::-1][n1:n2]  # []
                if len(bb_id) != 0:
                    self.run_bb_2(bb_id, t1, t2, ws)
                    print(time.time() - t2)
                    time.sleep(1)
                    mm += 1
                    if mm == 5:
                        try:
                            ws.close()
                        finally:
                            mm = 0
                            ws = self.bb_conn_1()
                            print('-t2')
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def bb_3(self, n1, n2):
        while True:
            t1 = time.strftime("%Y-%m-%d %X", time.localtime())
            t2 = time.time()
            try:

                sql = "SELECT game_id,region_id,competition_id FROM bisai_get_bb WHERE is_disabled != 0"
                id_all = self.run_sql_2(sql)
                bb_id = [(i[0], i[1], i[2]) for i in id_all][::-1][n1:n2]  # []

                if len(bb_id) != 0:
                    # self.run_bb(bb_id, t1, t2)

                    aa = []
                    id_nun = len(bb_id) // 10
                    num = len(bb_id) % 10
                    if num == 0:
                        pego = id_nun
                    else:
                        pego = id_nun + 1
                    for i in range(pego):
                        th_1 = threading.Thread(target=self.run_bb_2, args=(bb_id[i * 10:(i + 1) * 10], t1, t2))
                        th_1.start()
                        aa.append(th_1)

                    for i in aa:
                        i.join()
                    print(time.time() - t2)
                    time.sleep(1)
                else:
                    print("等等")
                    time.sleep(120)
            except Exception as e:
                print(e)
                time.sleep(20)

    def db_2(self):
        sql = "SELECT token FROM db_token"
        to = self.run_sql(sql)[0][0]
        uid = db_uid(to)
        while True:
            t1 = time.time()
            try:

                od_bb_id = select_gun("FB_game_id", 'bisai_od_bb_duiwu')
                id_all = self.run_sql(od_bb_id)
                fb_id = [i[0] for i in id_all][::-1]
                if len(fb_id) != 0:
                    if int(t1) % 120 == 0:
                        uid = db_uid(to)
                    da = db_conn(uid, to)
                    self.db_handle(da, fb_id)
                else:
                    print("等等")
                    time.sleep(120)
            except:
                time.sleep(2)
                continue
            print(time.time() - t1)
            time.sleep(2)

    def db(self):
        sql = "SELECT token FROM db_token"
        to = self.run_sql_2(sql)[0][0]
        uid = db_uid(to)
        while True:
            t1 = time.time()
            try:
                sql = "SELECT game_id FROM bisai_get_od WHERE is_disabled != 0"
                idall = self.run_sql_2(sql)
                fb_id = [i[0] for i in idall][::-1]
                if len(fb_id) != 0:
                    if int(t1) % 120 == 0:
                        uid = db_uid(to)
                    da = db_conn(uid, to)
                    self.db_handle(da, fb_id)
                else:
                    print("等等")
                    time.sleep(120)
            except:
                time.sleep(2)
                continue
            print(time.time() - t1)
            time.sleep(2)

# if __name__ == '__main__':
# uid = db_uid()
# while True:
#     aa = Conn()
#     try:
#         da = db_conn(uid)
#     except:
#         continue
#     aa.db_handle(da)
#     time.sleep(2)
#     print("*********")
#     aa = Run()
#     aa.bb_fb_1()
